/**
 * PagePropertyContent
 */

import React, { Component } from 'react';
import consts from "../../../consts/consts";
import storage from "../../../utils/storage";
import Validator from "../../../utils/validator/Validator";
import SingleUpload from "../../../utils/upload/SingleUpload";
import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import pageJumpActions from '../../../actions/Editor/pageJump';
import pageTimelinesActions from '../../../actions/Editor/pageTimelines';
import pagesActions from '../../../actions/Editor/pages';
import editorDialog from "../../../actions/Editor/dialog";
import ResourceDialog from '../../dialog/ResourceDialog'

class PagePropertyContent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pageJump: {},
            auto_turning: 0,
            turning_delay: 1,
            h5_shared_url: '',
            floating_screen: {
                url: "",
                custom: 0
            },
            showTips: false,
            turning_antype: 0
        };
    }
    getInitialState (){
        return {
            pageJump: {},
            auto_turning: 0,
            turning_delay: 1,
            h5_shared_url: '',
            floating_screen: {
                url: "",
                custom: 0
            },
            showTips: false,
            turning_antype: 0
        }
    }
    componentWillMount (){
        let self = this;
        let page = this.props.page;
        this.timer = setInterval(function (){
            var page = self.props.page;
            if (page){
                self.queryData();
                clearInterval(self.timer);
            }
        }, 10);
        this.everypage = {};
    }
    componentDidMount(){
        this.initElements();

        let defaultSettings = {
            md5Field: "music_md5",
            upload_url: storage.data.CONST.upload_url,
            placeholder: "请填写在线视频地址或者上传mp4格式文件",
            accept: "image/png,image/jpg,image/jpeg,image/PNG,image/JPG,image/JPEG"
        };

        let target = $('.shareIme');
        this.helper = new SingleUpload(target, this, defaultSettings);
    }
    componentWillUnmount (){
        clearInterval(this.timer);
    }
    queryData (){
        let page = this.props.page;
        this.setState({
            auto_turning: page.auto_turning,
            turning_delay: page.turning_delay || 1,
            floating_pics: page.floating_pics,
            floating_screen:{
                select_floating: page.select_floating || 0,
                custom: page.floating_screen ? page.floating_screen.custom : 0
            }
        });
    }
    initElements (){
        this.elements = {
            delayTimeIpt: $(this.refs.delayTimeIpt),
            antypeSelect: $(this.refs.antypeSelect)
        };
    }
    handleOnDelayTimeBlur (){
//        var root = this.props.root;
//        root.updateDelay(root.state.page);
    }
    handleOnChangeDelayTime (e){
        const { page,updatePage } = this.props;
        let input = $(e.target);
        let val = parseInt(input.val()) || 1;
        let param = {
            turning_delay: val > 60 ? 60 : val,
            page_id: page.page_id
        };
        updatePage(param);
    }
    handleOnAddResourceClick (){
        const {openDialog, closeDialog, editor}=this.props;
        openDialog('public/resourceDialog', ResourceDialog, {}, {
                closeDialog
            }
        );
//        var root = this.props.root;
//        root.openDialog(consts.DIALOG_TYPE.RESOURCE);
    }
    handleOnFloatingScreenChange (type, param){
        const {page,updatePage} = this.props;
        const {floating_screen} = page || {};
        floating_screen[type] = param;
        param = {
            floating_screen: floating_screen,
            page_id: page.page_id
        };
        updatePage(param);

    }
    handleOnChangePictureDialog (type, e){
        const {setState} = this.props;
//        if (type =='fixedBack'){
//            root.setState({
//                is_floating_screen: true
//            });
//        }
        console.log("open　dialog");
//        root.openDialog(consts.DIALOG_TYPE.UPLOAD_PICTURE);
    }
    handleOnPageJumpClick (type, val){
        let param = {};
        param[type] = !val;
        this.updatePageJump(param);
    }
    updatePageJump(pageJump){
        const {updatePageJump} = this.props;
        updatePageJump(pageJump);
    }
    handleOnPropertyChange (type, e){
        let input = this.focusItem = $(e.target);
        let val = input.val();
        val = parseFloat(val) || 0;

        const {pageJump} = this.props;

        let default_angle = {
            rotate_x: 0,
            rotate_y: 0,
            rotate_z: 0
        }
        let picture_angle = pageJump.picture_angle || default_angle;

        if (this.checkInputVaild(type, val)){
            if (type =='rotate_x'){
                picture_angle.rotate_x = val;
            } else if(type == 'rotate_y') {
                picture_angle.rotate_y = val;
            } else if(type == 'rotate_z') {
                picture_angle.rotate_z = val;
            }
            this.picture_angle = picture_angle;

            this.updatePageJump(picture_angle);
        }
    }
    handleOnPropertyUpdate (){
//        const { pageJump} = this.props;
//        this.updatePageJump(pageJump);
    }
    checkInputVaild (type, value, needAlert){
        let validators = [];
        let validator = Validator();

        validators.push({ validator: type });
        validator.addRule(value, validators);

        let errors = validator.execute();
        errors && needAlert && (alert(errors));

        return !errors;
    }
    handleOnAntypeChanged(e){
        const {page,pageTimelines,updatePageTimeline} = this.props;
        let element = $(e.target);
        let an_type = parseInt(element.val());

        updatePageTimeline({page_id:page.page_id,an_types: [{an_type: an_type }]});
    }
    handleOnAutoTurningClick (type,val){
        const {page,updatePage} = this.props;
        let param = {};
        param[type] = !val;
        param["page_id"] = page.page_id;
        updatePage(param);
    }
    open_screen_tips (){
        this.setState({
            showTips: !this.state.showTips
        });
    }
    render (){
        const {page,pageJump,pageTimelines,fromTemplate} = this.props;
        if (!page || !pageJump) return false;
        const {auto_turning,turning_delay,floating_screen,floating_pics} = page;
        let pageAnEvents = consts.PAGE_AN_EVENTS;
        let turning_loop = pageJump.turning_loop;
        let show_resource_picture = pageJump.show_resource_picture || 0;
        let rotate_x = pageJump.picture_angle ? pageJump.picture_angle.rotate_x || 0 : 0;
        let rotate_y = pageJump.picture_angle ? pageJump.picture_angle.rotate_y || 0 : 0;
        let rotate_z = pageJump.picture_angle ? pageJump.picture_angle.rotate_z || 0 : 0;
        let turning_antype = pageTimelines ? pageTimelines.an_types[0].an_type : 0;
        let custom = floating_screen ? floating_screen.custom : 0;
        let url = floating_screen ? floating_screen.url : "";
        let fixedSwitch = floating_screen ? floating_screen.switch : 0;
        let select_floating = floating_screen ? floating_screen.select_floating : 0;

        var delayNode = "";
        if (auto_turning){
            delayNode =
                <div className="yanchitime">
                    <span>{$._("Delay")}</span>
                    <span className="yan_second">s</span>
                    <input ref="delayTimeIpt" onBlur={() => this.handleOnDelayTimeBlur(0)} onChange={(e) => this.handleOnChangeDelayTime(e)} type="number" min="1" max="60" className="delayTime form-control" value={turning_delay} />
                </div>
        }

        var defaultBackImgNode = "";
        if (!custom){
           defaultBackImgNode =
               <div className="defaultBackImg">
                    <div className="screen-item" style={{backgroundImage:"url("+floating_pics[0]+")"}} onClick={(e) => this.handleOnFloatingScreenChange('select_floating', 0)} name="url">
                        <span className="icon-uniF52F" style={{display:select_floating ==0 ? "block" : "none"}}></span>
                    </div>
                    <div className="screen-item" style={{backgroundImage:"url("+floating_pics[1]+")"}} onClick={(e) => this.handleOnFloatingScreenChange('select_floating', 1)} name="url">
                        <span className="icon-uniF52F" style={{display:select_floating == 1 ? "block" : "none"}}></span>
                    </div>
                    <div className="screen-item" style={{backgroundImage:"url("+floating_pics[2]+")"}} onClick={(e) => this.handleOnFloatingScreenChange('select_floating', 2)} name="url">
                        <span className="icon-uniF52F" style={{display:select_floating == 2 ? "block" : "none"}}></span>
                    </div>
               </div>
        }

        var uploadedStyle = {};
        if (custom && url){
            // 上传后的样式
            uploadedStyle = {
                background: "url(" + url + ") no-repeat center",
                backgroundSize: "cover"
            };
        }

        var rowListBackImgNode = "";
        if (custom == 1){
            rowListBackImgNode =
                <div className="widget-meta-custom">
                    <div type="button" tabIndex="-1" className="custom-image-btn-img fixed_custom" onClick={() => this.handleOnChangePictureDialog("fixedBack")} style={uploadedStyle}>
                        <span className={"fixedBack " + (url ? "uploadedStyle" : "")} data-type="fixedBack">{$._("Upload custom image")}</span>
                    </div>
                    <div className="meta-custom-tips">{$._("Contains transparency PNG image, 720*1280px")}</div>
                </div>
        }

        var fixedNode = "";
        var heightStyle = {};
        if (fromTemplate && !fixedSwitch){
            fixedNode = "";
        } else {
            fixedNode = <div className="rowlist">
                    <div className="fixedSwitch">
                        <label>{$._("Fixed background")}</label>
                        <div onClick={(e) => this.handleOnFloatingScreenChange("switch",!fixedSwitch)} className={"screen-item repeat info-item-icon " + (fixedSwitch ? "icon-uniF52F" : "icon-uniF471")} name="switch"></div>
                        <div className="screen_btn" onClick={() => this.open_screen_tips()}>{$._("Example")}</div>
                        <div className="screen_tips" style={{display:this.state.showTips ? "block" : "none"}} onClick={() => this.open_screen_tips()}>
                            <img src="/static/idealsee/images/new_editor/editor/fixed_back.jpg" />
                        </div>
                    </div>
                    <div style={{display: fixedSwitch ? "block" :"none"}}>
                        <div className="standard">
                            <div className={"screen-item " +(!custom ? "activebtn" : "noactivebtn")} name="custom" id="red_change_custom" onClick={(e) => this.handleOnFloatingScreenChange("custom", 0)} name="custom">
                                <span>{$._("Default style")}</span>
                            </div>
                            <div className={"screen-item " +(custom == 1 ? "activebtn" : "noactivebtn")} name="custom" id="red_change_custom1" onClick={(e) => this.handleOnFloatingScreenChange("custom", 1)} name="custom">
                                <span>{$._("Custom")}</span>
                            </div>
                        </div>
                        {defaultBackImgNode}
                        {rowListBackImgNode}
                    </div>
            </div>

            heightStyle = {
                height: "470px",
            }
        }
        var display = {
            display: (fromTemplate ? "none" : "block")
        };
        return (
            <form noValidate className="property-container property" name="form.name" style={heightStyle}>
                <div className="page-property">
                    <div className="page-property-content">
                        <div className="page-content">
                            <div style={display} onClick={() => this.handleOnAddResourceClick()} type="button" className="addsu">
                                <span className="button-item">{$._("Importing footage")}</span>
                            </div>
                            <div className="yemianxunhuan">
                                <span className="pull-left spanPos">{$._("Page Loop")}</span>
                                <div onClick={() => this.handleOnPageJumpClick("turning_loop", turning_loop)} className={"page-item repeat info-item-icon " + (turning_loop ? "icon-uniF52F" : "icon-uniF471")} name="turning_loop"></div>
                            </div>
                            <div className="rowlist">
                                <span className="pull-left spanPos">{$._("AR lost after the work does not display plans")}</span>
                                <div onClick={() => this.handleOnPageJumpClick("show_resource_picture",show_resource_picture)} className={"page-item repeat info-item-icon " + (show_resource_picture ? "icon-uniF52F" : "icon-uniF471")} name="show_resource_picture"></div>
                            </div>
                            <div className="rowlist">
                                <div className="">{$._("Rotation angle after loss of AR")}</div>
                                <input className='form-control' type="number" name="rotate_x" placeholder="x" onChange={(e) => this.handleOnPropertyChange("rotate_x", e)} value={rotate_x} onBlur={() => this.handleOnPropertyUpdate()} />
                                <input className='form-control' type="number" name="rotate_z" placeholder="y" onChange={(e) => this.handleOnPropertyChange("rotate_z", e)} value={rotate_z} onBlur={() => this.handleOnPropertyUpdate()} />
                                <input className='form-control' type="number" name="rotate_y" placeholder="z" onChange={(e) => this.handleOnPropertyChange("rotate_y", e)} value={rotate_y} onBlur={() => this.handleOnPropertyUpdate()} />
                                <span className="page-angle">x</span>
                                <span className="page-angle">y</span>
                                <span className="page-angle">z</span>
                            </div>
                        </div>
                        <div className="turing_info">
                            <div className="now_title">{$._("Current page property")}</div>
                            <div className="qieyexiaoguo">
                                <span className="spanPos">{$._("Flip effect")}</span>
                                <select ref="antypeSelect" onChange={(e) => this.handleOnAntypeChanged(e)} data-turning-effect className="form-control" value={turning_antype}>
                                {
                                    pageAnEvents.map(function (anType){
                                        return (
                                            <option key={anType.an_type} className="anTypebtn" value={anType.an_type}>
                                                {anType.name}
                                            </option>
                                        )
                                    })
                                }
                                </select>
                            </div>
                            <div className="qieye">
                                <span>{$._("Auto turning")}</span>
                                <div onClick={() => this.handleOnAutoTurningClick("auto_turning",auto_turning)} className={"repeat info-item-icon " + (auto_turning ? "icon-uniF52F" : "icon-uniF471")}></div>
                            </div>
                            {delayNode}
                            {fixedNode}
                        </div>
                    </div>
                </div>
            </form>
        )
    }
 }

const mapStateToProps = ({ editor, widgets, timelines , pages, pageJump, pageTimelines}) => {
  const pageId = editor.selectedPageId;
  return {
      page: pages.filter(p => p.page_id === pageId)[0],
      pageJump,
      pageTimelines: pageTimelines.filter(p => p.page_id === pageId)[0]
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...pageJumpActions,...pageTimelinesActions,...pagesActions,...editorDialog}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(PagePropertyContent);
